import os
import json
import uuid
import zipfile
from flask import Flask, request, jsonify, send_from_directory
from werkzeug.utils import secure_filename
from utils.jupk_parser import parse_jupk  # 导入解析工具

app = Flask(__name__)

# 配置文件上传目录
UPLOAD_FOLDER_SOFTWARE = 'uploads/software'
UPLOAD_FOLDER_ICONS = 'uploads/icons'
ALLOWED_EXTENSIONS = {'jupk'}

app.config['UPLOAD_FOLDER_SOFTWARE'] = UPLOAD_FOLDER_SOFTWARE
app.config['UPLOAD_FOLDER_ICONS'] = UPLOAD_FOLDER_ICONS

# 确保上传目录存在
os.makedirs(UPLOAD_FOLDER_SOFTWARE, exist_ok=True)
os.makedirs(UPLOAD_FOLDER_ICONS, exist_ok=True)

# 数据存储文件
DATA_FILE = 'data/software.json'

# 初始化数据存储目录和文件
def initialize_data_file():
    """初始化数据存储目录和文件"""
    data_dir = os.path.dirname(DATA_FILE)
    if not os.path.exists(data_dir):
        os.makedirs(data_dir)
    if not os.path.exists(DATA_FILE):
        with open(DATA_FILE, 'w') as f:
            json.dump([], f)  # 初始化一个空列表

# 初始化数据文件
initialize_data_file()

def allowed_file(filename):
    """检查文件扩展名是否允许"""
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def save_software_data(data):
    """保存软件数据到 JSON 文件"""
    with open(DATA_FILE, 'w') as f:
        json.dump(data, f, indent=4)

def load_software_data():
    """从 JSON 文件加载软件数据"""
    with open(DATA_FILE, 'r') as f:
        return json.load(f)

def generate_unique_filename(original_filename):
    """生成唯一的文件名"""
    ext = original_filename.rsplit('.', 1)[1].lower()  # 获取文件扩展名
    unique_id = uuid.uuid4().hex  # 生成 UUID
    return f"{unique_id}.{ext}"

@app.route('/upload', methods=['POST'])
def upload_software():
    """上传软件包"""
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'}), 400

    software_file = request.files['file']

    if software_file.filename == '':
        return jsonify({'error': 'No selected file'}), 400

    if software_file and allowed_file(software_file.filename):
        # 生成唯一的文件名
        software_filename = generate_unique_filename(software_file.filename)
        software_path = os.path.join(app.config['UPLOAD_FOLDER_SOFTWARE'], software_filename)
        software_file.save(software_path)

        try:
            # 解析 .jupk 文件
            app_icon, app_package, icon_filename, install_log = parse_jupk(software_path)

            # 生成唯一的图标文件名
            icon_unique_filename = generate_unique_filename(icon_filename)
            icon_path = os.path.join(app.config['UPLOAD_FOLDER_ICONS'], icon_unique_filename)

            # 提取图标文件
            with zipfile.ZipFile(software_path, 'r') as zip_ref:
                with open(icon_path, 'wb') as icon_file:
                    icon_file.write(zip_ref.read(icon_filename))

            # 构建软件数据
            software_data = {
                'id': len(load_software_data()) + 1,
                'name': request.form.get('name', ''),
                'version': request.form.get('version', ''),
                'description': request.form.get('description', ''),
                'app_icon': app_icon,  # 应用图标
                'app_package': app_package,  # 应用包名
                'software_url': f'/download/software/{software_filename}',
                'icon_url': f'/download/icon/{icon_unique_filename}',
                'install_log': install_log  # 主引导文件内容
            }

            # 保存数据
            data = load_software_data()
            data.append(software_data)
            save_software_data(data)

            return jsonify(software_data), 201

        except Exception as e:
            return jsonify({'error': str(e)}), 400

    return jsonify({'error': 'File type not allowed'}), 400

@app.route('/download/software/<filename>', methods=['GET'])
def download_software(filename):
    """下载软件包"""
    return send_from_directory(app.config['UPLOAD_FOLDER_SOFTWARE'], filename)

@app.route('/download/icon/<filename>', methods=['GET'])
def download_icon(filename):
    """下载应用图标"""
    return send_from_directory(app.config['UPLOAD_FOLDER_ICONS'], filename)

@app.route('/software', methods=['GET'])
def list_software():
    """获取软件列表"""
    return jsonify(load_software_data())

@app.route('/software/<int:software_id>', methods=['GET'])
def get_software(software_id):
    """获取单个软件信息"""
    data = load_software_data()
    software = next((item for item in data if item['id'] == software_id), None)
    if software:
        return jsonify(software)
    return jsonify({'error': 'Software not found'}), 404

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=7690, debug=True)